package com.hilton.tigershark.downloads;

import java.util.GregorianCalendar;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class DownloadProvider extends ContentProvider {
    public static final String AUTHORITY = "com.hilton.tigershark.downloads.DownloadProvider";
    public static final String DB_FILE_NAME = "downloads.db";
    static final String TABLE_NAME = "downloads";
    private static final int URI_MATCH_DOWNLOADS = 10;
    private static final int URI_MATCH_DOWNLOADS_ID = 100;
    private static final String DEFAULT_SORT_BY = Downloads.CREATED + " DESC";
    private static final String TAG = null;
    private SQLiteOpenHelper mDatabaseHelper;
    
    private static UriMatcher URI_MATCHER =  new UriMatcher(UriMatcher.NO_MATCH);
    static {
	URI_MATCHER.addURI(AUTHORITY, TABLE_NAME, URI_MATCH_DOWNLOADS);
	URI_MATCHER.addURI(AUTHORITY, TABLE_NAME + "/#", URI_MATCH_DOWNLOADS_ID);
    };
    
    @Override
    public int delete(Uri uri, String where, String[] args) {
	final int which  = URI_MATCHER.match(uri);
	if (invalidUri(which)) {
	    throw new IllegalArgumentException("delete: bad Uri " + uri);
	}
	final int rows = mDatabaseHelper.getWritableDatabase().delete(TABLE_NAME, buildWhereClause(uri, where, which), args);
	getContext().getContentResolver().notifyChange(Downloads.CONTENT_URI, null);
	return rows;
    }

    @Override
    public String getType(Uri uri) {
        final int match = URI_MATCHER.match(uri);
        switch (match) {
        case URI_MATCH_DOWNLOADS:
            return "vnd.android.cursor.dir/downloads";
        case URI_MATCH_DOWNLOADS_ID:
            return "vnd.android.cursor.item/downloads";
        }
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
	final int which = URI_MATCHER.match(uri);
	if (which != URI_MATCH_DOWNLOADS) {
	    throw new IllegalArgumentException("Invalid Uri: " + uri);
	}
	if (!values.containsKey(Downloads.CREATED)) {
	    long now = new GregorianCalendar().getTimeInMillis();
	    values.put(Downloads.CREATED, now);
	}
	long row = mDatabaseHelper.getWritableDatabase().insert(TABLE_NAME, Downloads.URL, values);
	getContext().getContentResolver().notifyChange(Downloads.CONTENT_URI, null);
	return ContentUris.withAppendedId(Downloads.CONTENT_URI, row);
    }

    @Override
    public boolean onCreate() {
	mDatabaseHelper = new DownloadDBOpenHelper(getContext(), DB_FILE_NAME, null, 2);
	return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
	    String[] selectionArgs, String sortOrder) {
	final int which = URI_MATCHER.match(uri);
	if (invalidUri(which)) {
	    throw new IllegalArgumentException("query invalid Uri " + uri);
	}
	final String orderBy = TextUtils.isEmpty(sortOrder) ? DEFAULT_SORT_BY : sortOrder;
	Cursor cursor = mDatabaseHelper.getReadableDatabase().query(TABLE_NAME, 
		projection, buildWhereClause(uri, selection, which), selectionArgs, null, null, orderBy);
	return cursor;
    }

    private boolean invalidUri(final int which) {
	return which != URI_MATCH_DOWNLOADS && which != URI_MATCH_DOWNLOADS_ID;
    }

    private String buildWhereClause(Uri uri, String selection,
	    final int which) {
	StringBuilder whereClause = new StringBuilder();
	if (which == URI_MATCH_DOWNLOADS_ID) {
	    whereClause.append("(_id = ").append(uri.getPathSegments().get(1)).append(")");
	}
	if (selection != null && selection.length() > 0) {
	    if (whereClause.length() > 0) {
		whereClause.append(" AND ");
	    }
	    
	    whereClause.append('(');
	    whereClause.append(selection);
	    whereClause.append(')');
	}
	return whereClause.toString();
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
	final int which = URI_MATCHER.match(uri);
	if (invalidUri(which)) {
	    throw new IllegalArgumentException("update bad uri: " + uri);
	}
	final int rows = mDatabaseHelper.getWritableDatabase().update(TABLE_NAME, values, buildWhereClause(uri, selection, which), selectionArgs);
	if (!(values.size() == 1 && values.containsKey(Downloads.CURRENT_BYTES))) {
	    getContext().getContentResolver().notifyChange(Downloads.CONTENT_URI, null);
	}
	return rows;
    }

    public class DownloadDBOpenHelper extends SQLiteOpenHelper {
	public DownloadDBOpenHelper(Context context, String name, CursorFactory factory, int version) {
	    super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	    createTable(db);
	}

	private void createTable(SQLiteDatabase db) {
	    db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
		    Downloads._ID + " INTEGER PRIMARY KEY, " +
		    Downloads.URL + " TEXT, " +
		    Downloads.PATH + " TEXT, " + 
		    Downloads.FILENAME + " TEXT, " +
		    Downloads.MIME_TYPE + " TEXT, " +
		    Downloads.CURRENT_BYTES + " INTEGER DEFAULT 0, " +
		    Downloads.TOTAL_BYTES + " INTEGER DEFAULT 0," +
		    Downloads.CREATED + " DATE DEFAULT NOW, " +
		    Downloads.STATUS + " INTEGER DEFAULT 0);");
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	    
	}
    }
}